<?php

/**
 * 系统基础
 */

namespace app\member\api;

use \app\base\api\BaseApi;

class MemberApi extends BaseApi {

    public function __construct() {
        parent::__construct();
        $this->checkLogin();
    }

    /**
     * 检测登录
     */
    private function checkLogin() {
        if(!target('Member/Member', 'service')->checkUser($this->data['auth_uid'], $this->data['auth_token'])){
            $this->error(target('Member/Member', 'service')->getError(), 401);
        }
    }

    /**
     * 获取用户资料
     */
    public function info() {
        $info = target('Member/Member', 'service')->getUser($this->data['auth_uid']);
        if(empty($info)){
            $this->error(target('Member/Member', 'service')->getError());
        }
        $this->success('ok', $info);
    }

    /**
     * 更新用户资料
     */
    public function update() {
        $data = target('Member/Member', 'service')->updateUser($this->data['auth_uid'], $this->data);
        if(!$data){
            $this->error(target('Member/Member', 'service')->getError());
        }
        $this->success('资料保存成功!', $data);
    }

    /**
     * 更新头像
     */
    public function avatar() {

        if (empty($_FILES['file']['name'])) {
            $this->error('请选择头像！');
        }
        $service = target('Member/Member', 'service');
        $updateData = $service->upload($this->data['auth_uid'], 'jpg,png,bmp,jpeg', 128, 128);
        if(!$updateData){
            $this->error($service->getError());
        }
        $userData = [];
        $userData['user_id'] = $this->data['auth_uid'];
        $userData['avatar'] = $updateData['url'];
        $data = target('Member/MemberUser')->edit($userData);
        if(!$data){
            $this->error(target('Member/MemberUser')->getError());
        }
        $this->success('头像上传成功!', $updateData);
    }

    /**
     * 上传照片
     */
    public function upload() {

        if (empty($_FILES['file']['name'])) {
            $this->error('请选择文件！');
        }
        $service = target('Member/Member', 'service');
        $updateData = $service->upload($this->data['auth_uid'], 'jpg,png,bmp,jpeg', 800, 800);
        if(!$updateData){
            $this->error($service->getError());
        }
        $this->success('上传成功!', $updateData);
    }

}